<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2022-10-07
 * Time: 20:32
 */

namespace App\middleware;
use App\controller\dtk\Dtk;
use App\server\JwtAuth;
use support\exception\Unauthorized;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class UserAuth implements MiddlewareInterface
{
    private const JWT_KEY= 'NsU^biVNG#R@RXtJC^J8OO!qxHF';
    static $control=[
        \App\controller\xb\Index::class=>'xb',
        \App\controller\work\Order::class=>'order',
        \App\controller\wechat\App::class=>'wechat',
        \App\controller\dtk\Dtk::class=>'dtk'
    ];
    public function process(Request $request, callable $handler) : Response
    {
        $control=$request->controller;
        if(array_key_exists($control,self::$control)){
            $token=$request->header('Authorization');
            if(empty($token)){
                throw new Unauthorized('没有传入token');
            }
            $user =JwtAuth::verifyToken($token,self::JWT_KEY);
            $controller=self::$control[$control];
            $action=$request->action;;
            $request->user=$user;

            if(isset($user['role']) && in_array('admin',$user['role'])){
                return  $handler($request);
            }
            if(isset($user['role']) && in_array($controller,$user['role'])){
                return  $handler($request);
            }
            $permission=strtoupper($controller.'_'.$action);
            if(isset($user['permission']) && in_array($permission,$user['permission'])){
                return  $handler($request);
            }
            throw new Unauthorized('权限不足');
        }
        return $handler($request);
    }
}